﻿using MyToolkit.MVVM;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.Web.Syndication;
using Youtube_HD.Model;

namespace Youtube_HD.Services
{
    public class SearchViewModel : BaseViewModel, ISearchViewModel
    {
        public Dictionary<string, string> DataRequest { get; set; }
        public string KeyWordSearch { get; set; }

        IHttpChannel httpChannel;

        ObservableCollection<YoutubeVideo> moviesSearch;
        public ObservableCollection<YoutubeVideo> MoviesSearch
        {
            get
            {
                if (moviesSearch == null)
                    moviesSearch = new ObservableCollection<YoutubeVideo>();
                return moviesSearch;
            }
            set
            {
                moviesSearch = value;
                RaisePropertyChanged(() => MoviesSearch);
            }
        }
        ObservableCollection<YoutubeVideo> channels;
        public ObservableCollection<YoutubeVideo> Channels
        {
            get
            {
                if (channels == null)
                    channels = new ObservableCollection<YoutubeVideo>();
                return channels;
            }
            set
            {
                channels = value;
                RaisePropertyChanged(() => Channels);
            }
        }
        ObservableCollection<YoutubeVideo> playlists;
        public ObservableCollection<YoutubeVideo> Playlists
        {
            get
            {
                if (playlists == null)
                    playlists = new ObservableCollection<YoutubeVideo>();
                return playlists;
            }
            set
            {
                playlists = value;
                RaisePropertyChanged(() => Playlists);
            }
        }
        bool searchComplete = false;
        public bool SearchComplete
        {
            get
            {
                return searchComplete;
            }
            set
            {
                searchComplete = value;
                RaisePropertyChanged(() => SearchComplete);
            }
        }
        public SearchViewModel(IHttpChannel httpChannel)
        {
            this.httpChannel = httpChannel;
        }
        public async Task YoutubePlaylistSearch()
        {
            string urlData = Playlists[Playlists.Count - 1].NextPage;
            if (urlData == null)
                return;
            await GetPlayListData(urlData);
        }
        public async Task YoutubeVideosSearch()
        {
            string urlData = MoviesSearch[MoviesSearch.Count - 1].NextPage;
            if (urlData == null)
                return;
            await SearchMovies(urlData);

        }
        public async Task<feed> YoutubeVideosSearch(string keyWork, Dictionary<string, string> param)
        {
            KeyWordSearch = WebUtility.UrlEncode(keyWork.Trim());
            var dataParm = HttpChannel.GetQueryString(param).Remove(0, 1);
            if (!string.IsNullOrEmpty(dataParm))
            {
                dataParm = "https://gdata.youtube.com/feeds/api/videos?q=" + KeyWordSearch + "&" + dataParm;
            }
            await SearchMovies(dataParm);
            return null;
        }
        private async Task SearchMovies(string dataParm)
        {
            Debug.WriteLine(dataParm);
            SearchComplete = true;
            var getData = await httpChannel.GetDataYoutubeAsync(dataParm);
            if (getData != null)
            {
                var data = ModelCreator<feed>.s_CreateInstanceFromXml(getData);
                if (data.entry.Count() > 0)
                {
                    string nextPage = data.link[data.link.Count() - 1].href;
                    foreach (var u in data.entry)
                    {
                        var duration = u.group.duration.seconds;
                        string a = u.link[0].href.ToString().Remove(0, 32);
                        var youtubeList = new YoutubeVideo()
                        {
                            Description = u.group.description.Value,
                            PubDate = "Published: " + u.published.ToString("mm-dd-yyyy"),
                            Thumbnail = "https://i.ytimg.com/vi/" + u.group.videoid + "/default.jpg",
                            Title = u.title,
                            Id = a.Substring(0, 11),
                            Author = "Author: " + u.author.name,
                            ViewCount = "View: " + (u.statistics != null ? u.statistics.viewCount : 0),
                            Duration = "Duration: " + TimeSpan.FromSeconds(duration == 0 ? 0 : duration).Duration().ToString(),
                            NextPage = nextPage
                        };
                        MoviesSearch.Add(youtubeList);
                    }
                }
            }
            else
            {
                new MessageDialog("Search for " + KeyWordSearch + " not found").ShowAsync();
            }
            SearchComplete = false;
        }
        public async Task YoutubeChannelSearch()
        {
            string urlData = Channels[Channels.Count - 1].NextPage;
            if (urlData == null)
                return;
            await SearchChannels(urlData);
        }
        public async Task<Youtube_HD.Model.Channels.feed> YoutubeChannelsSearch(string keyWork, Dictionary<string, string> param)
        {

            string dataRequest = WebUtility.UrlEncode(keyWork.Trim());
            var dataParm = HttpChannel.GetQueryString(param).Remove(0, 1);
            if (!string.IsNullOrEmpty(dataParm))
            {
                dataRequest = dataRequest + "&" + dataParm;
            }
            string urlSearchChannels = "https://gdata.youtube.com/feeds/api/channels?q=" + dataRequest;
            await SearchChannels(urlSearchChannels);
            return null;
        }

        private async Task SearchChannels(string urlSearchChannels)
        {
            Debug.WriteLine(urlSearchChannels);
            SearchComplete = true;
            var getChannel = await httpChannel.GetDataYoutubeAsync(urlSearchChannels);
            if (!string.IsNullOrEmpty(getChannel))
            {

                var data = ModelCreator<Model.Channels.feed>.s_CreateInstanceFromXml(getChannel);
                if (data != null)
                {
                    string nextPage = data.link[data.link.Count() - 1].href;
                    foreach (var u in data.entry)
                    {
                        var youtubeList = new YoutubeVideo()
                        {
                            Thumbnail = u.thumbnail.url,
                            Title = u.title,
                            ChannelId = u.channelId,
                            Description = "Subscriber: " + u.channelStatistics.subscriberCount,
                            ViewCount = "Views: " + u.channelStatistics.viewCount,
                            NextPage = nextPage
                        };
                        Channels.Add(youtubeList);
                    }
                }
            }
            else
            {
                new MessageDialog("Search for " + KeyWordSearch + " not found").ShowAsync();
            }
            SearchComplete = false;
        }
        public async Task<Youtube_HD.Model.PlayList.feed> YoutubePlaylistSearch(string keyWork, Dictionary<string, string> param)
        {

            string dataRequest = WebUtility.UrlEncode(keyWork.Trim());
            var dataParm = HttpChannel.GetQueryString(param).Remove(0, 1);
            if (!string.IsNullOrEmpty(dataParm))
            {
                dataRequest = dataRequest + "&" + dataParm;
            }
            await GetPlayListData(dataRequest);

            return null;
        }

        private async Task GetPlayListData(string dataRequest)
        {
            string urlSearchPlaylist = "https://gdata.youtube.com/feeds/api/playlists/snippets?q=" + dataRequest;
            var getPlayList = await httpChannel.GetDataYoutubeAsync(urlSearchPlaylist);

            if (!string.IsNullOrEmpty(getPlayList))
            {

                var data = ModelCreator<Youtube_HD.Model.PlayList.feed>.s_CreateInstanceFromXml(getPlayList);
                if (data != null)
                {
                    foreach (var u in data.entry)
                    {
                        if (u.group != null)
                        {
                            var youtubeList = new YoutubeVideo()
                            {
                                PubDate = "Published: " + u.published.ToString(),
                                Thumbnail = u.group[u.group.Count() - 1].url,
                                Title = u.title,
                                PlayListId = u.playlistId,
                                ViewCount = "Total Sections: " + (u.countHint != null ? u.countHint : 0),
                            };
                            Playlists.Add(youtubeList);
                        }
                    }
                }
            }
            else
            {
                new MessageDialog("Search for " + KeyWordSearch + " not found").ShowAsync();
            }
        }
        public async Task<feed> YoutubeSearch(string url)
        {
            feed youtubeVideo = new feed();
            try
            {
                var getData = await httpChannel.GetDataYoutubeAsync(url);
                if (!string.IsNullOrEmpty(getData))
                {
                    youtubeVideo = ModelCreator<feed>.s_CreateInstanceFromXml(getData);
                }
            }
            catch
            {
                return null;
            }
            return youtubeVideo;
        }
    }
}
